package com.aidex.quartz.service.impl;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.bo.BusinessSetBo;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.domain.enums.MessageTypeEnum;
import com.aidex.biz.messageSend.MessageSendService;
import com.aidex.biz.service.*;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.quartz.service.TaskService;
import com.aidex.quartz.util.DateUtils;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.ISysUserService;
import com.aidex.system.service.SysDictDataService;
import com.aidex.wxCompany.WxWrokMessageService;
import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

@Service
public class TaskServiceImpl implements TaskService {

    private static final Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private MessageInfoService messageInfoService;
    @Autowired
    private ShareLogService shareLogService;
    @Autowired
    private CustomerReceiveService customerReceiveService;
    @Autowired
    private PushRuleUserService pushRuleUserService;
    @Autowired
    private TempShareService tempShareService;
    @Autowired
    private TempShareRuleService tempShareRuleService;
    @Autowired
    private BusinessSetService businessSetService;

    @Autowired
    private CustomerTestService customerTestService;
    @Autowired
    private WxWrokMessageService wxWrokMessageService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ToHomeService toHomeService;
    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private JinjianInfoService jinjianInfoService;

    @Autowired
    private XiansuoChengbenLogService xiansuoChengbenLogService;


    @Autowired
    private JinjianBillService jinjianBillService;


    @Autowired
    private SysDictDataService sysDictDataService;

    /**
     * times时间内未跟进重新分配
     *
     * @param times
     * @param setTimeStr
     * @param endTimeStr
     * @param countInTimes
     * @throws ParseException
     */
    @Override
    public void taskCustomerNotGenJinRep(Integer times, String setTimeStr, String endTimeStr, Integer countInTimes) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        // 9.00-23.00
        Date setTime = sdf.parse(setTimeStr + ":00:00");
        Date endTime = sdf.parse(endTimeStr + ":00:00");
        LocalTime now = LocalTime.now();
        // 定义时间段
        LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(), setTime.getSeconds()); // 上午9点
        LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(), endTime.getSeconds()); // 晚上23点
        if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
            BusinessSetBo businessSet = new BusinessSetBo();
            businessSet.setTime(times);
            businessSet.setCountInTimes(countInTimes);
            List<Customer> customerList = customerService.findNotGen(businessSet);
            if (null != customerList && !customerList.isEmpty()) {
                for (Customer customer : customerList) {
                    //删除我的接单
                    CustomerReceive customerReceive = new CustomerReceive();
                    customerReceive.setUserId(customer.getUserId());
                    customerReceive.setCustomerId(customer.getId());
                    customerReceiveService.deleteCustomerReceive(customerReceive);

                    //扣除分配次数
                    ShareLog shareLogParam = new ShareLog();
                    shareLogParam.setUserId(customer.getUserId());
                    shareLogParam.setCustomerId(customer.getId());
                    ShareLog shareLog = shareLogService.findOne(shareLogParam);
                    if (null != shareLog && null != shareLog.getRuleuserId()) {
                        PushRuleUser user = pushRuleUserService.get(shareLog.getRuleuserId());
                        if (null != user) {
                            if (null != user.getSharedCount() && user.getSharedCount() > 0) {
                                user.setSharedCount(user.getSharedCount() - 1);
                            }
                            if (null != user.getTotalCount() && user.getTotalCount() > 0) {
                                user.setTotalCount(user.getTotalCount() - 1);
                            }
                            //删除临时表 确保不占用分配顺序 2025-5-17 改为占用名额ß
//                            TempShareRule tempShareRule=new TempShareRule();
//                            tempShareRule.setRuleId(user.getRuleId());
//                            tempShareRule.setLaiyuan(customer.getLaiyuan());
//                            tempShareRuleService.deleteTempShareRuleByRuleIdLaiyuan(tempShareRule);
//
//                            PushRuleUser pushRuleUser=new PushRuleUser();
//                            pushRuleUser.setRuleId(user.getRuleId());
//                            pushRuleUser.setLaiyuan(customer.getLaiyuan());
//                            pushRuleUser.setCity(customer.getCityName());
//                            List<PushRuleUser> pushRuleUserList = pushRuleUserService.findList(pushRuleUser);
//                            if (!pushRuleUserList.isEmpty()) {
//                                String[] ids = new String[pushRuleUserList.size()];
//                                for (int i = 0; i < pushRuleUserList.size(); i++) {
//                                    ids[i] = pushRuleUserList.get(i).getId();
//                                }
//                                tempShareService.deleteAllByUserRuleIds(ids);
//                            }
                        }
                        pushRuleUserService.save(user);
                    }


                    if (customerService.updateNotGen(customer) > 0) {
                        CustomerDongtai customerDongtai = new CustomerDongtai();
                        customerDongtai.setCustomerId(customer.getId());
                        customerDongtai.setType(DongTaiTypeEnum.UPDATE_INFO.getStatus());
                        ;
                        customerDongtai.setContent("【" + times + "】分钟内未跟进，系统重新分配");
                        customerDongtaiService.save(customerDongtai);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type", "xiezuCus");
                        jsonObject.put("msg", "客户【" + customer.getCusName() + "】因规定时间没跟进，将重新分配");
                        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                                customer.getUserId(), jsonObject.toJSONString());
                        messageInfoService.sendMsg(customer, MessageTypeEnum.XZKH, jsonObject.getString("msg"));
                    }
                }
            }
        }
    }

    /**
     * 未接6小时流转（9.00-18.00），非工作时间不计入，三次未接流转  或的关系，
     * 有一个满足就流转  针对新客户，流转两次就不再流转，锁定的除外
     * 10分钟一次
     *
     * @throws Exception
     */
    @Override
    public void taskWeiJieCustomerToShare() throws Exception {
        // 读取配置参数
        BusinessSet businessSet = businessSetService.get("index_set");
        if (null != businessSet) {
            CustomerTest customerTest = new CustomerTest();
            customerTest.setTestType("2");
            customerTestService.deleteCustomerTestByType(customerTest);
            BusinessSetBo businessSetBo = null;
            List<Customer> movingToGinghaiOverTimeList = new ArrayList<>();
            // 未接超时流转
            if (null != businessSet.getIsWjTimesOpen() && 1 == businessSet.getIsWjTimesOpen()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getWjTimes());
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date setTime = sdf.parse(businessSet.getWjWorkStartTime());
                Date endTime = sdf.parse(businessSet.getWjWorkEndTime());
                LocalTime now = LocalTime.now();
                // 定义时间段
                LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(), setTime.getSeconds());
                LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(), endTime.getSeconds());
                List<Customer> customerList = customerService.findWjExceedTimeToShareList(businessSetBo);
                for (Customer customer : customerList) {
                    if (null != customer.getEndTime()) {
                        // 判断是否是工作时间段内超过6小时
                        LocalDateTime localDateEndTime = customer.getEndTime().toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDateTime();
                        if (DateUtils.isExceededHours(localDateEndTime, businessSet.getWjTimes(), startTime1, endTime1)) {
//                            CustomerTest cusTest = new CustomerTest();
//                            cusTest.setTestType("2");
//                            cusTest.setUserId(customer.getUserId());
//                            cusTest.setUserName(customer.getUserName());
//                            cusTest.setDeptId(customer.getDeptId());
//                            cusTest.setCustomerId(customer.getId());
//                            cusTest.setStatus("0");
//                            cusTest.setBeforeStatus(customer.getStatus());
//                            cusTest.setRemark("未接超[" + businessSet.getWjTimes() + "]小时流转");
//                            customerTestService.save(cusTest);
                            movingToGinghaiOverTimeList.add(customer);
                        }
                    }
                }

                if (!movingToGinghaiOverTimeList.isEmpty()) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("list", movingToGinghaiOverTimeList);
                    params.put("type", 3);
                    params.put("content", "系统操作-未接超" + businessSet.getWjTimes() + "（小时）流转");
                    customerDongtaiService.insertBatch(params);
                    customerService.updateStatusToWeiJie(movingToGinghaiOverTimeList);
                }
            }

            // 未接超次数流转
            if (null != businessSet.getIsWjCountsOpen() && 1 == businessSet.getIsWjCountsOpen()) {
                businessSetBo = new BusinessSetBo();
                businessSetBo.setTime(businessSet.getWjCounts());
                List<Customer> customerList = customerService.findWjExceedCountToShareList(businessSetBo);

                if (!customerList.isEmpty()) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("list", customerList);
                    params.put("type", 3);
                    params.put("content", "系统操作-未接超" + businessSet.getWjTimes() + "（次）流转");
                    customerDongtaiService.insertBatch(params);
                    customerService.updateStatusToWeiJie(customerList);
                }
//                for (Customer customer : customerList) {
//                    CustomerTest cusTest = new CustomerTest();
//                    cusTest.setTestType("2");
//                    cusTest.setUserId(customer.getUserId());
//                    cusTest.setUserName(customer.getUserName());
//                    cusTest.setDeptId(customer.getDeptId());
//                    cusTest.setCustomerId(customer.getId());
//                    cusTest.setStatus("0");
//                    cusTest.setBeforeStatus(customer.getStatus());
//                    cusTest.setRemark("未接超[" + businessSet.getWjCounts() + "]次流转");
//                    customerTestService.save(cusTest);
//                }
            }


        }
    }

    @Override
    public void taskGetAllWxUserIds() {
        List<SysUser> list = sysUserService.findAllSendWxMsgUserList();
        for (SysUser user : list) {
            if (StringUtils.isNotNull(user.getPhonenumber())) {
                Map<String, Object> result = wxWrokMessageService.getUserIdByPhone(user.getPhonenumber());
                if ((boolean) result.get("isSuccess")) {
                    // 同步到用户表
                    user.setUserPinyin(result.get("userId").toString());
                    sysUserService.updateUserPinyin(user);
                }
            }
        }
    }

    @Override
    public void taskWxReminder() {
        //1.即将上门提醒
        Integer beforeTime = 30;
        ToHome toHome = toHomeService.findOneNearToHome(beforeTime);
        String wxMsgModel = ConfigUtils.getConfigValueByKey("wxWork.model.toHome.near");
        if (StringUtils.isNotNull(wxMsgModel)) {
            String toHomeCompanyId = toHome.getToHomeCompanyId();
            if (StringUtils.isNull(toHomeCompanyId)) {
                toHomeCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
            }
            Company company = companyService.get(toHomeCompanyId);
            if (null != company) {
                String cusName = Objects.toString(toHome.getCusName(), "");
                String companyName = company.getCompanyName();
                String toHomeTime = Objects.toString(toHome.getToHomeTime(), "");
                String content = String.format(wxMsgModel.replace("\\n", "\n"),
                        companyName,
                        cusName,
                        toHomeTime
                );
                SysUser sysUser = sysUserService.getUserCache(toHome.getUserId());
                String robotAddress = company.getRemark();
                messageSendService.sendMessageWxWorkToGroup(robotAddress, content, new String[]{sysUser.getPhonenumber()});
            }
        }

        //2.签到后10分钟未接单提醒

    }

    @Override
    @Transactional(readOnly = false)
    public void taskDataCleaning() {
        //1.历史成交客户，成本数据清洗。 之前成交时没有线索成本记录 无法统计成本 故需要数据清洗
        // 先查进件表，通过customerId和laiyuan取线索成本最新的记录
        System.out.print("数据清洗逻辑开始\r\n");
        JinjianInfo jinjianInfo = jinjianInfoService.findOneJinjianCleaning();
        String xscbLogId = jinjianInfoService.jinjianCleaning(jinjianInfo);
        if (StringUtils.isNotNull(xscbLogId)) {
            jinjianInfo.setXscbLogId(xscbLogId);
            jinjianInfo.setCleaningStatus(1);
            jinjianInfoService.save(jinjianInfo);
        }
    }
}
